<?php

if ( ! function_exists('is_php'))
{
    /**
     * Determines if the current version of PHP is equal to or greater than the supplied value
     *
     * @param	string
     * @return	bool	TRUE if the current version is $version or higher
     */
    function is_php($version)
    {
        static $_is_php;
        $version = (string) $version;

        if ( !isset($_is_php[$version]))
        {
            $_is_php[$version] = version_compare(PHP_VERSION, $version, '>=');
        }
        return $_is_php[$version];
    }
}

if ( ! function_exists('remove_invisible_characters'))
{
    /**
     * Remove Invisible Characters
     * @param	string
     * @param	bool
     * @return	string
     */
    function remove_invisible_characters($str, $url_encoded = TRUE)
    {
        $non_displayables = array();
        if ($url_encoded)
        {
            $non_displayables[] = '/%0[0-8bcef]/i';	// url encoded 00-08, 11, 12, 14, 15
            $non_displayables[] = '/%1[0-9a-f]/i';	// url encoded 16-31
            $non_displayables[] = '/%7f/i';	// url encoded 127
        }
        $non_displayables[] = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S';	// 00-08, 11, 12, 14-31, 127
        do
        {
            $str = preg_replace($non_displayables, '', $str, -1, $count);
        }
        while ($count);
        return $str;
    }
}

function daddslashes($string) {
    return is_array($string) ? array_map('daddslashes', $string) : addslashes($string);
}

function dhtmlspecialchars($string) {
    return is_array($string) ? array_map('dhtmlspecialchars', $string) : htmlspecialchars($string);
}

function dhtmlspecialcharsDecode($string) {
    return is_array($string) ? array_map('dhtmlspecialcharsDecode', $string) : htmlspecialchars_decode($string);
}

function dstripTags($string) {
    return is_array($string) ? array_map('dstripTags', $string) : strip_tags($string);
}

function dstripslashes($string) {
    return is_array($string) ? array_map('dstripslashes', $string) : stripslashes($string);
}

function dtrim($string) {
    return str_replace(array(chr(10), chr(13), urldecode('%C2%A0'), "\t", ' '), array('', '', '', '', ''), $string);
}

function is_robot($ua = '') {
    return preg_match("/(spider|bot|crawl|slurp|lycos|robozilla)/i", $ua ? $ua : $_SERVER['HTTP_USER_AGENT']);
}

function is_touch() {
    return preg_match("/(iPhone|iPad|iPod|Android)/i", $_SERVER['HTTP_USER_AGENT']) ? 1 : 0;
}

function is_mob($par = '') {
    return preg_match("/(iPhone|iPad|iPod|Android|Phone|mobile)/i", ($par ? $par : $_SERVER['HTTP_USER_AGENT'])) ? 1 : 0;
}

function strip_uri($uri) {
    if(strpos($uri, '%') !== false) {
        while($uri != urldecode($uri)) {
            $uri = urldecode($uri);
        }
    }
    if(strpos($uri, '<') !== false || strpos($uri, "'") !== false || strpos($uri, '"') !== false) {
        dhttp(403, 0);
    }
}

function dhttp($status, $exit = 1) {
    switch($status) {
        case '301': @header("HTTP/1.1 301 Moved Permanently"); break;
        case '403': @header("HTTP/1.1 403 Forbidden"); break;
        case '404': @header("HTTP/1.1 404 Not Found"); break;
        case '503': @header("HTTP/1.1 503 Service Unavailable"); break;
    }
    if($exit) exit;
}

function strip_key($array) {
    foreach($array as $k=>$v) {
        if(!preg_match("/^[a-z0-9_\-]{1,64}$/i", $k)) {
            dhttp(403, 0);
        }
        if(is_array($v)) strip_key($v);
    }
}

function strip_str($string) {
    return str_replace(array('\\','"', "'"), array('', '', ''), $string);
}

function is_md5($password) {
    return preg_match("/^[a-f0-9]{32}$/", $password);
}

function strip_sql($string) {
    if(is_array($string)) {
        return array_map('strip_sql', $string);
    } else {
        //过滤sql
        return $string;
    }
}

function dd(...$args){
    ob_end_clean();
    echo "<pre>";
    var_dump($args);
    echo "</pre>";
    exit;
}

function dump(...$args){
    echo "<pre>";
    var_dump($args);
    echo "</pre>";
}

/**
 * 配置助手函数
 */
function config($name=null,$default=null){
    if($name){
        $val=\ltcms\lib\Config::getInstance()->get($name);
        return isset($val)?$val:$default;
    }else{
        return \ltcms\lib\Config::getInstance();
    }
}

/**
 * 插件-配置助手函数
 * @param $name
 * @return bool|mixed
 */
function configPlugin($name=null,$default=null){
    if($name){
        $val=\ltcms\lib\Config::getInstance()->getPlugin($name);
        return isset($val)?$val:$default;
    }else{
        return \ltcms\lib\Config::getInstance();
    }
}

/**
 * 安装检测
 * @param $name
 * @return bool|mixed
 */
function install(){
    return \ltcms\lib\Install::getInstance();
}

/**
 * 语言助手函数
 * @param $name
 * @return bool|mixed
 */
function lang($name=null,$params=null){
    if($name){
        return \ltcms\lib\Lang::getInstance()->get($name,$params);
    }else{
        return \ltcms\lib\Lang::getInstance();
    }
}

/**
 * 语言助手函数
 * @param $name
 * @return bool|mixed
 */
function langPlugin($name=null,$params=null){
    if($name){
        return \ltcms\lib\Lang::getInstance()->getPlugin($name,$params);
    }else{
        return \ltcms\lib\Lang::getInstance();
    }
}

/**
 * 语言助手函数 如果没有对应值返回原值
 * @param $name
 * @return bool|mixed
 */
function lang2($name=null,$params=null){

    $ret=lang($name,$params);

    if($ret){
        return $ret;
    }else{
        return $name;
    }
}

/**
 * 请求助手函数
 * @param $name
 * @return bool|mixed
 */
function request($name="",$default=null){
    if($name){
        return \ltcms\lib\Request::getInstance()->param($name,$default);
    }else{
        return \ltcms\lib\Request::getInstance();
    }
}

if (!function_exists('uniqueStr')) {
    /**
     * 唯一字符串
     * @return string
     */
    function uniqueStr()
    {
        $md_str = time();
        $md_str .= uniqid(mt_rand(), true);
        $md_str .= rand(10000, 99999);
        $charid = strtoupper(md5($md_str));
        return $charid;
    }
}

/**
 * 容器助手函数
 * @param $name
 * @return bool|mixed
 */
function container($name=""){
    if($name){
        return \ltcms\container\Container::getInstance()->make($name);
    }else{
        return \ltcms\container\Container::getInstance();
    }
}

/**
 * 应用助手函数
 * @param $name
 * @return bool|mixed
 */
function app($name=""){
    return container($name);
}

/**
 * 容器助手函数
 * @param $name
 * @return bool|mixed
 */
function service(){
    return \ltcms\service\Service::getInstance();
}

/**
 * 视图管理
 * @param $name
 * @return bool|mixed
 */
function viewManage(){
    return \ltcms\response\ViewManage::getInstance();
}

/**
 * 事件函数
 * @param $name
 * @return bool|mixed
 */
function event(){
    return \ltcms\lib\Event::getInstance();
}

/**
 * 返回数据库实例
 */
function Db(){
    return \ltcms\db\Db::getInstance()->changeConnect("default");
}

/**
 * 返回环境变量实例
 */
function env(){
    return \ltcms\lib\Env::getInstance();
}

/**
 * 返回缓存实例
 */
function cache(){
    return \ltcms\cache\Cache::getInstance();
}

/**
 * 返回session实例
 */
function session(){
    return \ltcms\session\Sessions::getInstance();
}

/**
 * 获取数组中的值
 */
function getVal($data,$key,$default=null){
    return isset($data[$key])?$data[$key]:$default;
}

/**
 * 获取中间件对象
 */
function middleware(){
    return \ltcms\middleware\Middleware::getInstance();
}

/**
 * 获取分页对象
 */
function pageBar($data){
    $page=new \ltcms\lib\Page();
    return $page->getPageBar($data);
}

/**
 * 返回安全类对象
 */
function security(){
    return \ltcms\lib\Security::getInstance();
}

/**
 * 获取路由对象
 */
function router(){
    return \ltcms\route\Router::getInstance();
}

/**
 * 获取多应用对象
 */
function multipleApp(){
    return \ltcms\lib\MultipleApp::getInstance();
}

/**
 * 获取错误处理对象
 */
function error(){
    return \ltcms\lib\ErrorClass::getInstance();
}

if (!function_exists('jsonResponse')) {
    /**
     * json响应
     * @param array $data
     * @param int $code
     * @param array $header
     * @param array $options
     * @return \ltcms\response\Json|\ltcms\response\Jsonp
     */
    function jsonResponse($data = [], $code = 200, $header = [], $options = [])
    {
        $isJsonp=request()->isJsonp();
        if($isJsonp){
            return jsonp($data,$code,$header,$options);
        }else{
            return json($data,$code,$header,$options);
        }
    }
}

if (!function_exists('json')) {
    /**
     * @param mixed $data    返回的数据
     * @param int   $code    状态码
     * @param array $header  头部
     * @param array $options 参数
     * @return \ltcms\response\Json
     */
    function json($data = [], $code = 200, $header = [], $options = [])
    {
        return \ltcms\response\Response::create($data, 'json', $code)->header($header)->options($options);
    }
}

if (!function_exists('jsonp')) {
    /**
     * @param mixed $data    返回的数据
     * @param int   $code    状态码
     * @param array $header  头部
     * @param array $options 参数
     * @return \ltcms\response\Jsonp
     */
    function jsonp($data = [], $code = 200, $header = [], $options = [])
    {
        return \ltcms\response\Response::create($data, 'jsonp', $code)->header($header)->options($options);
    }
}

if (!function_exists('response')) {
    /**
     * @param mixed      $data   输出数据
     * @param int|string $code   状态码
     * @param array      $header 头信息
     * @param string     $type
     */
    function response($data = '', $code = 200, $header = [], $type = 'html')
    {
        return \ltcms\response\Response::create($data, $type, $code)->header($header);
    }
}

if (!function_exists('view')) {
    /**
     * 渲染模板输出
     * @param string   $template 模板文件
     * @param array    $vars     模板变量
     * @param int      $code     状态码
     * @param callable $filter   内容过滤
     */
    function view($template = '', $vars = [], $code = 200)
    {
        return \ltcms\response\Response::create($template, 'view', $code)->assign($vars);
    }
}

if (!function_exists('redirect')) {
    /**
     * @param string $url  重定向地址
     * @param int    $code 状态码
     */
    function redirect(string $url = '', int $code = 302)
    {
        return \ltcms\response\Response::create($url, 'redirect', $code);
    }
}

if (!function_exists('validate')) {
    /**
     * 验证器
     * @return \ltcms\lib\Validate
     */
    function validate()
    {
        return \ltcms\lib\Validate::getInstance();
    }
}

/**
 * 获取头部信息
 */
if (!function_exists('getallheaders')) {
    function getallheaders(){
        $header = [];
        $server = $_SERVER;
        foreach ($server as $key => $val) {
            if (0 === strpos($key, 'HTTP_')) {
                $key          = str_replace('_', '-', strtolower(substr($key, 5)));
                $header[$key] = $val;
            }
        }
        if (isset($server['CONTENT_TYPE'])) {
            $header['content-type'] = $server['CONTENT_TYPE'];
        }
        if (isset($server['CONTENT_LENGTH'])) {
            $header['content-length'] = $server['CONTENT_LENGTH'];
        }
        return $header;
    }
}

/**
 * 获取头部信息
 */
if (!function_exists('getHeader')) {
    /**
     * 获取头部信息
     * @param null $name
     */
    function getHeader($name=null)
    {
        if (function_exists('apache_request_headers') && $result = apache_request_headers()) {
            $header = $result;
        } else {
            $header = [];
            $server = $_SERVER;
            foreach ($server as $key => $val) {
                if (0 === strpos($key, 'HTTP_')) {
                    $key          = str_replace('_', '-', strtolower(substr($key, 5)));
                    $header[$key] = $val;
                }
            }
            if (isset($server['CONTENT_TYPE'])) {
                $header['content-type'] = $server['CONTENT_TYPE'];
            }
            if (isset($server['CONTENT_LENGTH'])) {
                $header['content-length'] = $server['CONTENT_LENGTH'];
            }
        }
        return $header;
    }
}

/**
 * 数组融合
 * @param $dir
 * @param array $fs
 * @return array
 */
function arrFusion($arr1, $arr2) {
    foreach($arr2 as $key=>$val) {
        if(isset($arr1[$key])){
            if(is_array($val) && is_array($arr1[$key])) {
                $arr1[$key] = arrFusion($arr1[$key],$val);
            } else {
                $arr1[$key] = $val;
            }
        }else{
            $arr1[$key] = $val;
        }
    }
    return $arr1;
}

/**
 * 递归改变数组增加前缀
 * @param $array
 * @param string $case
 * @return array
 */
function recursive_array_add_pre($array, $pre = '',$level=null, $deth=1) {
    $result = [];
    foreach ($array as $key => $value) {
        // 转换键的大小写
        $key = $pre.$key;
        // 如果值是一个数组，递归调用函数
        if (is_array($value)) {
            if(!is_null($level)){
                if($level < $deth){
                    $result[$key] = recursive_array_add_pre($value, $pre,$level,$deth + 1);
                }else{
                    $result[$key] = recursive_array_add_pre($value, "",null,$deth + 1);
                }
            }else{
                $result[$key] = recursive_array_add_pre($value, $pre,$level,$deth + 1);
            }
        } else {
            $result[$key] = $value;
        }
    }
    return $result;
}

/**
 * 设置数据
 * @param  array  $data 数据源
 * @param  string $name 字段名
 * @param  mixed  $default 默认值
 * @return mixed
 */
function setData($name,$value,$data=array())
{
    $names=explode('.', $name);
    $last=count($names) -1;
    $second=array();
    foreach ($names as $key=>$val) {
        if($key==$last){
            if($last >0){
                $element[$val]=$value;
            }else{
                $second[$val]=$value;
            }
        }else{
            if(isset($element)){
                $element[$val]=array();
                $element=&$element[$val];
            }else{
                $second[$val]=array();
                $element=&$second[$val];
            }
        }
    }
    if($data){
        return mergeArr($data,$second);
    }
    return $second;
}

/**
 * 获取数据
 * @param  array  $data 数据源
 * @param  string $name 字段名
 * @param  mixed  $default 默认值
 * @return mixed
 */
function getData($data,$name,$default = null)
{
    foreach (explode('.', $name) as $val) {
        if (isset($data[$val])) {
            $data = $data[$val];
        } else {
            return $default;
        }
    }
    return $data;
}

if (!function_exists('publicPath')) {
    /**
     * 获取 public 根目录
     *
     * @param string $path
     * @return string
     */
    function publicPath($path = '')
    {
        return LTCMS_ROOT . '/public/'  . ($path ? trim($path, "/") . "/" : $path);
    }
}

if (!function_exists('runtimePath')) {
    /**
     * 获取 runtime 根目录
     *
     * @param string $path
     * @return string
     */
    function runtimePath($path = '')
    {
        return LTCMS_ROOT . '/runtime/'  . ($path ? trim($path, "/") . "/" : $path);
    }
}

if (!function_exists('check_bom')) {
    /**
     * check utf8 bom
     *
     * @param $content
     */
    function check_bom(&$content) {
        $charset[1] = substr($content, 0, 1);
        $charset[2] = substr($content, 1, 1);
        $charset[3] = substr($content, 2, 1);
        if (ord($charset[1]) == 239 && ord($charset[2]) == 187 && ord($charset[3]) == 191) {
            $content = substr($content, 3);
        }
    }
}

if (!function_exists('isWritable')) {
    /**
     * 检测文件是否可写
     * @param $file
     * @return bool
     */
    function isWritable($file){
        $writeable = false;
        if(is_dir($file)){
            $dir = $file;
            if ($fp = @fopen("$dir/test.txt", 'w')) {
                @fclose($fp);
                @unlink("$dir/test.txt");
                $writeable = true;
            }
        } else {
            @makeDir(dirname($file));
            if(is_file($file)){
                if ($fp = @fopen($file, 'a+')) {
                    @fclose($fp);
                    $writeable = true;
                }
            }
        }
        return $writeable;
    }
}

/**
 * 插件注册-注册路由
 */
function pluginRegisterRoute($path){
    if(is_dir($path)){
        $folders = glob($path . "/*.php");
        if($folders){
            foreach($folders as $folder){
                @include_once $folder;
            }
        }
    }
}

/**
 * 插件注册-注册服务
 */
function pluginRegisterService($path){
    if(is_dir($path)){
        $folders = glob($path . '/*');
        if($folders){
            foreach($folders as $folder){
                $classNamespace = str_replace(LTCMS_ROOT . "/", "", $folder);
                $classNamespace = str_replace("/", "\\", $classNamespace);
                $classNamespace = str_replace(".php", "", $classNamespace);
                if (class_exists($classNamespace)) {
                    $controllerObj = new $classNamespace();
                    if (method_exists($controllerObj, "register")) {
                        $controllerObj->register();
                    }
                }
            }
        }
    }
}

/**
 * 插件注册-加载自定义函数
 */
function pluginHelp($path){
    if(is_dir($path)){
        $folders = glob($path . "/*.php");
        if($folders){
            foreach($folders as $folder){
                @include_once $folder;
            }
        }
    }
}
